#include <REGX52.H>

sbit DS1302_IO=P3^4;
sbit DS1302_CE=P3^5;
sbit DS1302_SCLK=P3^6;
#define DS_1302_YEAR	0x8C 	//将写年寄存器重命名为DS_1302_YEAR
#define DS_1302_MONTH	0x88 
#define DS_1302_DATE	0x86
#define DS_1302_HOUR	0x84 
#define DS_1302_MINUTE	0x82 
#define DS_1302_SECOND	0x80 
#define DS_1302_DAY		0x8A
#define DS_1302_WP		0x8E

unsigned char DS_1302_TIME[]={24,5,3,10,12,12,5};//定义数组保存时，年，年月日时分秒星期

void DS1302_Init()	//初始化DS1302,将CE,SCLE置低电平
{
	DS1302_CE=0;
	DS1302_SCLK=0;
}

void DS1302_WriteByte(unsigned char Command,Data)	//Command:第一个字节内容 Data：第二个字节内容
{													//写入数据
	unsigned char i;
	DS1302_CE=1;
	for(i=0;i<8;i++)
	{
	DS1302_IO=Command&(0x01<<i);
	DS1302_SCLK=1;	//由于51单片机运行速度慢，可以置高电平后直接置低电平
	DS1302_SCLK=0;
	}
	for(i=0;i<8;i++)
	{
	DS1302_IO=Data&(0x01<<i);
	DS1302_SCLK=1;	
	DS1302_SCLK=0;
	}
	DS1302_CE=0;
}

unsigned char DS1302_ReadByte(unsigned char Command)	//读出数据
{
	unsigned char i,Data=0x00;
	Command|=0x01;
	DS1302_CE=1;
	for(i=0;i<8;i++)
	{
		DS1302_IO=Command&(0x01<<i);
		DS1302_SCLK=0;
		DS1302_SCLK=1;
	}
	for(i=0;i<8;i++)
	{
		DS1302_SCLK=1;	
		DS1302_SCLK=0;
		if(DS1302_IO){Data|=(0x01<<i);}
	}
	DS1302_CE=0;
	DS1302_IO=0;
	return Data;
}

void Set_Time()	//定义函数将数组内容存到函数里
{
	DS1302_WriteByte(DS_1302_WP,0x00);
	DS1302_WriteByte(DS_1302_YEAR,DS_1302_TIME[0]/10*16+DS_1302_TIME[0]%10);
	DS1302_WriteByte(DS_1302_MONTH,DS_1302_TIME[1]/10*16+DS_1302_TIME[1]%10);
	DS1302_WriteByte(DS_1302_DATE,DS_1302_TIME[2]/10*16+DS_1302_TIME[2]%10);
	DS1302_WriteByte(DS_1302_HOUR,DS_1302_TIME[3]/10*16+DS_1302_TIME[3]%10);
	DS1302_WriteByte(DS_1302_MINUTE,DS_1302_TIME[4]/16*10+DS_1302_TIME[4]%10);
	DS1302_WriteByte(DS_1302_SECOND,DS_1302_TIME[5]/16*10+DS_1302_TIME[5]%10);
	DS1302_WriteByte(DS_1302_DAY,DS_1302_TIME[6]/10*16+DS_1302_TIME[6]%10);
	DS1302_WriteByte(DS_1302_WP,0x80);
}

void Read_Time()	//读出数组内容
{
	unsigned char Timp;
	Timp=DS1302_ReadByte(DS_1302_YEAR);
	DS_1302_TIME[0]=Timp/16*10+Timp%16;
	
	Timp=DS1302_ReadByte(DS_1302_MONTH);
	DS_1302_TIME[1]=Timp/16*10+Timp%16;
	
	Timp=DS1302_ReadByte(DS_1302_DATE);
	DS_1302_TIME[2]=Timp/16*10+Timp%16;
	
	Timp=DS1302_ReadByte(DS_1302_HOUR);
	DS_1302_TIME[3]=Timp/16*10+Timp%16;
	
	Timp=DS1302_ReadByte(DS_1302_MINUTE);
	DS_1302_TIME[4]=Timp/16*10+Timp%16;
	
	Timp=DS1302_ReadByte(DS_1302_SECOND);
	DS_1302_TIME[5]=Timp/16*10+Timp%16;
	
	Timp=DS1302_ReadByte(DS_1302_DAY);
	DS_1302_TIME[6]=Timp/16*10+Timp%16;
}